<?php
include_once "mdbtable.php";

class MPlatezh extends MDbTable {

	public $table = "platezh";

	protected function _createSqlByFilters($filters)
	{
		$CI = &get_instance();
		$this->db->select('t.*');
		foreach($filters as $filter_key => $filter_value)
		{
			switch($filter_key)
			{
				case 'add_fields':
					foreach($filter_value as $f)
					{
						switch($f)
						{
							case "can_delete":
								$this->db->select("if(exists(select null from ".$this->db->dbprefix.$CI->MSchetFix->table." where schet_id = t.schet_id and time_add > t.time_add limit 1), 0, 1) can_delete", false);
								break;

							case "schet_name":
								$this->db->join($CI->MSchet->table.' s', 's.id = t.schet_id');
								$this->db->select("concat(s.name, ' ', s.valuta) ".$f, false);
								break;
						}
					}
					break;

			}
		}
		return parent::_createSqlByFilters($filters);
	}


	public function getMyListByDateBuy($date, $from_user_id)
	{
		$CI = &get_instance();
		$this->db->select("p.*, u.email, u.fio, s.name schet_name");
		$this->db->from($this->table." p");
		$this->db->join($CI->MSchet->table." s", 's.id = p.schet_id');
		$this->db->join($CI->MUser->table." u", 'u.id = s.user_id');
		$where = array();
		$where['p.from_date'] = $date;
		$where['s.user_id'] = Auth::$user_id;
		$this->db->where($where);
		$this->db->where_in('p.type', array('buy', 'buy.drugoy', 'buy.des', 'buy.other'));
		$res = $this->db->get();
		$rows = $res->result('array');
		$out = array();
		foreach ($rows as $row)
		{
			$this->_modifyRow($row);
			$out[$row['id']] = $row;
		}
		return $out;
	}

	public function getMyListByDateSell($date, $to_user_id)
	{
		$CI = &get_instance();
		$this->db->select("p.*, s.name schet_name, u.fio, u.email");
		$this->db->from($this->table." p");
		$this->db->join($CI->MSchet->table." s", 's.id = p.schet_id');
		$this->db->join($CI->MUser->table." u", 'u.id = s.user_id');
		$where = array();
		$where['p.from_date'] = $date;
		$where['s.user_id'] = Auth::$user_id;
		$this->db->where($where);
		$this->db->where_in('p.type', array('sell', 'sell.drugoy', 'sell.des', 'sell.other'));
		$res = $this->db->get();
		$rows = $res->result('array');
		$out = array();
		foreach ($rows as $row)
		{
			$this->_modifyRow($row);
			$out[$row['id']] = $row;
		}
		return $out;
	}

	public function insert($arr, &$id)
	{
		$arr['time_add'] = time();
		parent::insert($arr, $id);
	}

	public function getPlatezhiByOpers($opers_id)
	{
		$CI = &get_instance();
		$this->db->select('p.*, o.id oper_id, concat(s.name, " ", s.valuta) schet_name');
		$this->db->from($CI->MOper->table.' o');
		$this->db->join($this->table.' p', 'o.platezh_id = p.id');
		$this->db->join($CI->MSchet->table.' s', 'p.schet_id = s.id');
		$this->db->where_in('o.id', $opers_id);
		$rows = $this->db->get()->result_array();
		$out = array();
		foreach($rows as $row)
		{
			$out[$row['oper_id']] = $row;
		}
		return $out;
	}




}

